import React from "react";
import Child from "./child.";

// 计数例子

// 定时器，网络请求，事件监听，在组件被销毁前都应得到相应的处理

const MyAPI = {
    count:0,
    subscribe(cb){
        this.intervaId = setInterval(() =>{
          this.count+=1
          cb(this.count);
        },1000)
    },
    unSubscribe(){
        clearInterval(this.intervaId);
        this.reset();
    },
    reset(){
        this.count = 0;
    }
}

export default class Parent extends React.Component{

    state = {
        count:0
    }

    componentDidMount(){
        MyAPI.subscribe((currentCount) =>{
           this.setState({
               count:currentCount
           })
        })
    }
    
    // 组件销毁前处理
    componentWillUnmount(){
        MyAPI.unSubscribe();
    }

    render(){
        console.log("parent->render")
        return(
            <div>
                parent:{this.state.count}
                <Child num = {this.state.count}/>
            </div>
        )
    }
}